<template>
  <div class="score-ranking-view">
    <!-- 排行榜控制面板 -->
    <div class="ranking-controls">
      <el-form :model="rankingForm" inline>
        <el-form-item label="项目">
          <el-select v-model="rankingForm.projectId" placeholder="选择项目" style="width: 200px" @change="handleProjectChange">
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="轮次">
          <el-select v-model="rankingForm.round" placeholder="选择轮次" style="width: 120px" @change="handleRoundChange">
            <el-option
              v-for="round in roundOptions"
              :key="round.value"
              :label="round.label"
              :value="round.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshRanking" :loading="loading">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 排行榜内容 -->
    <div class="ranking-content">
      <el-empty v-if="!loading && (!rankingData || rankingData.length === 0)" description="暂无排名数据" />

      <el-skeleton v-else-if="loading" :rows="5" animated />

      <div v-else class="ranking-list">
        <!-- 前三名特殊展示 -->
        <div class="podium-section" v-if="rankingData.length >= 3">
          <div class="podium">
            <div class="podium-item silver" data-rank="2">
              <div class="medal-icon">🥈</div>
              <div class="podium-info">
                <div class="student-name">{{ rankingData[1]?.student?.name || '-' }}</div>
                <div class="student-details">{{ rankingData[1]?.student?.department || '-' }}</div>
                <div class="score-display">
                  <span class="score-value">{{ rankingData[1]?.score || '-' }}</span>
                  <span class="score-unit">{{ rankingData[1]?.unit || '' }}</span>
                </div>
              </div>
              <div class="podium-position">2</div>
            </div>

            <div class="podium-item gold" data-rank="1">
              <div class="medal-icon">🥇</div>
              <div class="podium-info">
                <div class="student-name">{{ rankingData[0]?.student?.name || '-' }}</div>
                <div class="student-details">{{ rankingData[0]?.student?.department || '-' }}</div>
                <div class="score-display">
                  <span class="score-value" :class="{ 'record-breaking': rankingData[0]?.isRecord }">
                    {{ rankingData[0]?.score || '-' }}
                  </span>
                  <span class="score-unit">{{ rankingData[0]?.unit || '' }}</span>
                  <el-tag v-if="rankingData[0]?.isRecord" type="danger" size="small">
                    破纪录
                  </el-tag>
                </div>
              </div>
              <div class="podium-position">1</div>
            </div>

            <div class="podium-item bronze" data-rank="3">
              <div class="medal-icon">🥉</div>
              <div class="podium-info">
                <div class="student-name">{{ rankingData[2]?.student?.name || '-' }}</div>
                <div class="student-details">{{ rankingData[2]?.student?.department || '-' }}</div>
                <div class="score-display">
                  <span class="score-value">{{ rankingData[2]?.score || '-' }}</span>
                  <span class="score-unit">{{ rankingData[2]?.unit || '' }}</span>
                </div>
              </div>
              <div class="podium-position">3</div>
            </div>
          </div>
        </div>

        <!-- 完整排名列表 -->
        <div class="ranking-table-section">
          <h3 class="section-title">完整排名</h3>
          <el-table :data="rankingData" stripe style="width: 100%" @row-click="handleRowClick">
            <el-table-column label="排名" width="80" align="center">
              <template #default="{ row }">
                <div class="rank-display" :class="getRankingClass(row.rank)">
                  <span v-if="row.rank <= 3" class="medal">{{ getMedalIcon(row.rank) }}</span>
                  <span v-else class="rank-number">{{ row.rank }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="学生信息" min-width="200">
              <template #default="{ row }">
                <div class="student-info">
                  <el-avatar :size="32" :src="row.student?.avatar">
                    {{ row.student?.name?.charAt(0) || '学' }}
                  </el-avatar>
                  <div class="student-details">
                    <div class="student-name">{{ row.student?.name || '-' }}</div>
                    <div class="student-meta">
                      {{ row.student?.studentNumber || '-' }} · {{ row.student?.department || '-' }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="成绩" width="120" align="center">
              <template #default="{ row }">
                <div class="score-display">
                  <span class="score-value" :class="{ 'record-breaking': row.isRecord }">
                    {{ row.score || '-' }}
                  </span>
                  <span class="score-unit">{{ row.unit || '' }}</span>
                  <el-tag v-if="row.isRecord" type="danger" size="small">
                    破纪录
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="轮次" width="100" align="center">
              <template #default="{ row }">
                {{ getRoundText(row.round) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" align="center">
              <template #default="{ row }">
                <el-button-group size="small">
                  <el-button type="primary" @click.stop="handleViewDetail(row)">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button type="success" @click.stop="handleGenerateCertificate(row)">
                    <el-icon><Document /></el-icon>
                  </el-button>
                  <el-button type="info" @click.stop="handleShare(row)">
                    <el-icon><Share /></el-icon>
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh, View, Document, Share
} from '@element-plus/icons-vue'
import { getScoreRanking, getProjectPage } from '@/api'

// 组件属性
const props = defineProps({
  projectId: {
    type: [String, Number],
    default: null
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 组件事件
const emit = defineEmits([
  'view-detail',
  'generate-certificate',
  'share'
])

// 排名数据
const rankingData = ref([])
const loading = ref(false)

// 项目选项
const projectOptions = ref([])

// 排行榜表单
const rankingForm = reactive({
  projectId: props.projectId,
  round: null
})

// 轮次选项
const roundOptions = ref([
  { value: null, label: '全部轮次' },
  { value: 1, label: '第1轮' },
  { value: 2, label: '第2轮' },
  { value: 3, label: '第3轮' },
  { value: 4, label: '决赛' }
])

// 获取排名样式类
const getRankingClass = (rank) => {
  if (rank === 1) return 'gold'
  if (rank === 2) return 'silver'
  if (rank === 3) return 'bronze'
  return ''
}

// 获取奖牌图标
const getMedalIcon = (rank) => {
  if (rank === 1) return '🥇'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return ''
}

// 获取轮次文本
const getRoundText = (round) => {
  const roundMap = {
    1: '第1轮',
    2: '第2轮',
    3: '第3轮',
    4: '决赛'
  }
  return roundMap[round] || '-'
}

// 加载项目选项
const loadProjectOptions = async () => {
  try {
    const response = await getProjectPage(1, 1000, {})
    if (response.code === 200) {
      projectOptions.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 加载排名数据
const loadRankingData = async () => {
  if (!rankingForm.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }

  loading.value = true
  try {
    const response = await getScoreRanking(rankingForm.projectId, rankingForm.round)
    if (response.code === 200) {
      rankingData.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取排名数据失败')
    }
  } catch (error) {
    console.error('获取排名数据失败:', error)
    ElMessage.error('获取排名数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新排名
const refreshRanking = () => {
  loadRankingData()
}

// 处理项目变化
const handleProjectChange = () => {
  loadRankingData()
}

// 处理轮次变化
const handleRoundChange = () => {
  loadRankingData()
}

// 处理行点击
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 查看详情
const handleViewDetail = (row) => {
  emit('view-detail', row)
}

// 生成证书
const handleGenerateCertificate = (row) => {
  emit('generate-certificate', row)
}

// 分享
const handleShare = (row) => {
  emit('share', row)
}

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    rankingForm.projectId = newProjectId
    loadRankingData()
  }
})

// 组件挂载
onMounted(() => {
  loadProjectOptions()
  if (rankingForm.projectId) {
    loadRankingData()
  }
})
</script>

<style scoped>
.score-ranking-view {
  width: 100%;
}

.ranking-controls {
  background-color: white;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.ranking-content {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.podium-section {
  margin-bottom: 32px;
}

.podium {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 20px;
  margin: 32px 0;
}

.podium-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  border-radius: 12px;
  padding: 20px;
  min-width: 200px;
  transition: all 0.3s ease;
}

.podium-item.gold {
  background: linear-gradient(135deg, #fff9e6, #ffed4e);
  box-shadow: 0 8px 25px rgba(255, 215, 0, 0.2);
  transform: scale(1.05);
}

.podium-item.silver {
  background: linear-gradient(135deg, #f8f8f8, #e8e8e8);
  box-shadow: 0 6px 20px rgba(192, 192, 192, 0.2);
}

.podium-item.bronze {
  background: linear-gradient(135deg, #fdf6e6, #f4e4d4);
  box-shadow: 0 6px 20px rgba(205, 127, 50, 0.2);
}

.podium-item:hover {
  transform: translateY(-5px);
}

.medal-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.podium-info {
  flex: 1;
}

.student-name {
  font-weight: 600;
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 4px;
}

.student-details {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 12px;
}

.score-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  flex-wrap: wrap;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.score-value.record-breaking {
  color: #e74c3c;
  animation: pulse 1.5s infinite;
}

.score-unit {
  font-size: 14px;
  color: #7f8c8d;
}

.podium-position {
  margin-top: 12px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.podium-item.gold .podium-position {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
}

.podium-item.silver .podium-position {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #696969;
}

.podium-item.bronze .podium-position {
  background: linear-gradient(135deg, #cd7f32, #e4a853);
  color: #8b4513;
}

.ranking-table-section {
  margin-top: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.rank-display {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: bold;
}

.rank-display.gold {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b8860b;
}

.rank-display.silver {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #696969;
}

.rank-display.bronze {
  background: linear-gradient(135deg, #cd7f32, #e4a853);
  color: #8b4513;
}

.medal {
  font-size: 16px;
}

.rank-number {
  font-size: 14px;
}

.student-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.student-details {
  flex: 1;
}

.student-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 2px;
}

.student-meta {
  font-size: 12px;
  color: #7f8c8d;
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .podium {
    flex-direction: column;
    align-items: center;
    gap: 16px;
  }

  .podium-item {
    width: 100%;
    max-width: 300px;
  }

  .podium-item.gold {
    transform: scale(1);
  }

  .student-name {
    font-size: 16px;
  }

  .score-value {
    font-size: 20px;
  }
}
</style>